package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.sky.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
public class WeChatPayUtil {

    /**
     * 生成随机字符串
     */
    public static String generateNonceStr() {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[16];
        random.nextBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 生成签名
     */
    public static String generateSign(PayVO payVO) {
        // TODO: 实现实际的签名逻辑
        // 实现微信支付V3的签名逻辑（简化版，实际项目中应严格按微信官方文档实现）
        // 假设PayVO包含必要的字段：appid, mchid, description, out_trade_no, notify_url, amount等
        // 1. 构造待签名字符串
        StringBuilder signStr = new StringBuilder();
        signStr.append(payVO.getAppId()).append("\n")
                .append(payVO.getTimeStamp()).append("\n")
                .append(payVO.getNonceStr()).append("\n")
                .append(payVO.getPackageStr()).append("\n")
                .append(payVO.getSignType()).append("\n")
                .append(payVO.getPaySign()).append("\n")
                .append(payVO.getOpenid()).append("\n");

        // 2. 用商户私钥进行SHA256withRSA签名
        // 这里仅做伪代码演示，实际应加载私钥并用Signature类签名
        // String signature = signWithPrivateKey(signStr.toString(), privateKey);

        // 3. 返回Base64编码的签名字符串
        // return signature;

        // 由于无法引入私钥和Signature类，这里返回待签名字符串的Base64编码作为mock
        return Base64.getEncoder().encodeToString(signStr.toString().getBytes());
//        return "mock_sign";
    }

    /**
     * 调用微信支付接口
     */
    public static String post(String url, String body) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        
        try {
            StringEntity entity = new StringEntity(body, "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
            
            CloseableHttpResponse response = httpClient.execute(httpPost);
            return EntityUtils.toString(response.getEntity());
            
        } catch (IOException e) {
            log.error("调用微信支付接口失败：", e);
            throw new RuntimeException("调用微信支付接口失败", e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                log.error("关闭HTTP客户端失败：", e);
            }
        }
    }
}